var KOC = require("koc.common.utils");
var StateData = require("../statedata");
var DALFactory = require("../../lib/dal/dal-factory");
var Interface_QQConnect = require("../../lib/interface-qqconnect");
var Interface_Weibo = require("../../lib/interface-weibo");
var Interface_Weixin = require("../../lib/interface-weixin");

module.exports = {
  Service: function (req, res) {
    switch (req.params.type) {
      //region QQConnect
      case "qqconnect.tologin":
        oauthFactory.ToLogin(req, res, "QQConnect");
        return;
      case "qqconnect.token":
        oauthFactory.QQConnect.Token(req, res);
        return;
      //endregion
      //region Weibo
      case "weibo.tologin":
        oauthFactory.ToLogin(req, res, "Weibo");
        return;
      case "weibo.token":
        oauthFactory.Weibo.Token(req, res);
        return;
      //endregion
      //region Weixin
      case "weixin.tologin":
        oauthFactory.ToLogin(req, res, "Weixin");
        return;
      case "weixin.token":
        oauthFactory.Weixin.Token(req, res);
        return;
      //endregion
    }
    res.jsonp({flag: -9999, msg: "未知的请求"});
  }
};

var oauthFactory = {
  ToLogin: function (req, res, Type) {
    if (StateData.Value(req, res).IsLogin) {
      res.jsonp({flag: -1, msg: "您已经登录"});
      return;
    }
    StateData.Cookie.RoomID.Set(res, req.params.RoomID);
    StateData.Cookie.SignUp_Url.Set(res, req.params.SignUp_Url);
    switch (Type) {
      case "QQConnect":
        res.redirect(Interface_QQConnect.OAuth_LoginUrl());
        break;
      case "Weibo":
        res.redirect(Interface_Weibo.OAuth_LoginUrl());
        break;
      case "Weixin":
        res.redirect(Interface_Weixin.OAuth_LoginUrl());
        break;
      default:
        res.jsonp({flag: 1, msg: "错误的参数"});
        break;
    }
  },
  QQConnect: {
    Token: function (req, res) {
      var _parm = {
        Code: req.params.code,
        State: req.params.state,
        Channel_ID: StateData.Cookie.ChannelID.Get(req),
        Inviter_ID: StateData.Cookie.InviterID.Get(req),
        Room_ID: StateData.Cookie.RoomID.Get(req),
        SignUp_Url: StateData.Cookie.SignUp_Url.Get(req)
      };
      KOC.Async.series([
        //获取Token
        function (callback) {
          Interface_QQConnect.OAuth_Token(_parm.Code, function (retValue) {
            if (retValue.hasError) {
              callback(retValue);
              return;
            }
            _parm.AccessToken = retValue.returnObject.AccessToken;
            _parm.ExpiresIn = retValue.returnObject.ExpiresIn;
            _parm.RefreshToken = retValue.returnObject.RefreshToken;
            callback();
          });
        },
        //获取OpenID
        function (callback) {
          Interface_QQConnect.OAuth_OpenID(_parm.AccessToken, function (retValue) {
            if (retValue.hasError) {
              callback(retValue);
              return;
            }
            _parm.OpenID = retValue.returnObject.OpenID;
            callback();
          });
        },
        //读取用户信息
        function (callback) {
          Interface_QQConnect.Get_User_Info(_parm.AccessToken, _parm.OpenID, function (retValue) {
            if (retValue.hasError) {
              callback(retValue);
              return;
            }
            switch (retValue.returnObject.gender) {
              case "男":
                _parm.Sex = 1;
                break;
              case "女":
                _parm.Sex = 2;
                break;
              default:
                _parm.Sex = -1;
                break;
            }
            if (retValue.returnObject.nickname) {
              _parm.NickName = retValue.returnObject.nickname;
            }
            callback();
          });
        },
        //调用用户登录方法
        function (callback) {
          DALFactory.Business.User_LoginQQ({
            User_ID: StateData.Value(req, res).User_ID,
            OAuth_QQ_ID: _parm.OpenID,
            OAuth_QQ_Token: _parm.AccessToken,
            OAuth_QQ_ExpiresIn: _parm.ExpiresIn,
            OAuth_QQ_RefreshToken: _parm.RefreshToken,
            NickName: _parm.NickName,
            Sex: _parm.Sex,
            Channel_ID: _parm.Channel_ID,
            Inviter_ID: _parm.Inviter_ID,
            Room_ID: _parm.Room_ID,
            SignUp_Origin: 0,
            SignUp_Url: _parm.SignUp_Url,
            Create_IP: KOC.StringUtils.GetClientIP(req)
          }, function (retValue) {
            if (retValue.hasError) {
              callback(retValue);
              return;
            }
            _parm.StateData = retValue.returnObject;
            callback();
          });
        }
      ], function (retValue) {
        if (retValue) {
          res.jsonp({flag: retValue.errorCode, msg: retValue.message});
          return;
        }
        //写入session
        StateData.Set(req, res, _parm.StateData);
        //页面转向
        res.redirect("/oauthlogin/success/");
      });
    }
  },
  Weibo: {
    Token: function (req, res) {
      var _parm = {
        Code: req.params.code,
        Channel_ID: StateData.Cookie.ChannelID.Get(req),
        Inviter_ID: StateData.Cookie.InviterID.Get(req),
        Room_ID: StateData.Cookie.RoomID.Get(req),
        SignUp_Url: StateData.Cookie.SignUp_Url.Get(req)
      };
      KOC.Async.series([
        //获取Token
        function (callback) {
          Interface_Weibo.OAuth_Token(_parm.Code, function (retValue) {
            if (retValue.hasError) {
              callback(retValue);
              return;
            }
            _parm.AccessToken = retValue.returnObject.Access_Token;
            _parm.ExpiresIn = retValue.returnObject.Expires_In;
            callback();
          });
        },
        //获取UID
        function (callback) {
          Interface_Weibo.OAuth_UID(_parm.AccessToken, function (retValue) {
            if (retValue.hasError) {
              callback(retValue);
              return;
            }
            _parm.UID = retValue.returnObject.UID;
            callback();
          });
        },
        //读取用户信息
        function (callback) {
          Interface_Weibo.Get_User_Info(_parm.AccessToken, _parm.UID, function (retValue) {
            if (retValue.hasError) {
              callback(retValue);
              return;
            }
            _parm.Sex = retValue.returnObject.gender == '女' ? 2 : 1;
            _parm.NickName = retValue.returnObject.screen_name || '';
            callback();
          });
        },
        //调用用户登录方法
        function (callback) {
          DALFactory.Business.User_LoginWeibo({
            OAuth_Weibo_ID: _parm.UID,
            OAuth_Weibo_Token: _parm.AccessToken,
            OAuth_Weibo_ExpiresIn: _parm.ExpiresIn,
            NickName: _parm.NickName,
            Sex: _parm.Sex,
            Channel_ID: _parm.Channel_ID,
            Inviter_ID: _parm.Inviter_ID,
            Room_ID: _parm.Room_ID,
            SignUp_Origin: 0,
            SignUp_Url: _parm.SignUp_Url,
            Create_IP: KOC.StringUtils.GetClientIP(req)
          }, function (retValue) {
            if (retValue.hasError) {
              callback(retValue);
              return;
            }
            _parm.StateData = retValue.returnObject;
            callback();
          });
        }
      ], function (retValue) {
        if (retValue) {
          res.jsonp({flag: retValue.errorCode, msg: retValue.message});
          return;
        }
        //写入session
        StateData.Set(req, res, _parm.StateData);
        //页面转向
        res.redirect("/oauthlogin/success/");
      });
    }
  },
  Weixin: {
    Token: function (req, res) {
      var _parm = {
        Code: req.params.code,
        State: req.params.state,
        Channel_ID: StateData.Cookie.ChannelID.Get(req),
        Inviter_ID: StateData.Cookie.InviterID.Get(req),
        Room_ID: StateData.Cookie.RoomID.Get(req),
        SignUp_Url: StateData.Cookie.SignUp_Url.Get(req)
      };
      KOC.Async.series([
        //获取Token
        function (callback) {
          Interface_Weixin.OAuth_Token(_parm.Code, function (retValue) {
            if (retValue.hasError) {
              callback(retValue);
              return;
            }
            _parm.AccessToken = retValue.returnObject.AccessToken;
            _parm.ExpiresIn = retValue.returnObject.ExpiresIn;
            _parm.RefreshToken = retValue.returnObject.RefreshToken;
            _parm.OpenID = retValue.returnObject.OpenID;
            callback();
          });
        },
        //读取用户信息
        function (callback) {
          Interface_Weixin.Get_User_Info(_parm.AccessToken, _parm.OpenID, function (retValue) {
            if (retValue.hasError) {
              callback(retValue);
              return;
            }
            _parm.NickName = retValue.returnObject.nickname;
            _parm.Unionid = retValue.returnObject.unionid;
            _parm.Sex = retValue.returnObject.sex;
            callback();
          });
        },
        //调用用户登录方法
        function (callback) {
          DALFactory.Business.User_LoginWeixin({
            User_ID: StateData.Value(req, res).User_ID,
            OAuth_Weixin_ID: _parm.OpenID,
            OAuth_Weixin_UNIONID: _parm.Unionid,
            OAuth_Weixin_Token: _parm.AccessToken,
            OAuth_Weixin_ExpiresIn: _parm.ExpiresIn,
            OAuth_Weixin_RefreshToken: _parm.RefreshToken,
            NickName: _parm.NickName,
            Sex: _parm.Sex,
            Channel_ID: _parm.Channel_ID,
            Inviter_ID: _parm.Inviter_ID,
            Room_ID: _parm.Room_ID,
            SignUp_Origin: 0,
            SignUp_Url: _parm.SignUp_Url,
            Create_IP: KOC.StringUtils.GetClientIP(req)
          }, function (retValue) {
            if (retValue.hasError) {
              callback(retValue);
              return;
            }
            _parm.StateData = retValue.returnObject;
            callback();
          });
        }
      ], function (retValue) {
        if (retValue) {
          res.jsonp({flag: retValue.errorCode, msg: retValue.message});
          return;
        }
        //写入session
        StateData.Set(req, res, _parm.StateData);
        //页面转向
        res.redirect("/oauthlogin/success/");
      });
    }
  }
};